import { PureComponent } from 'react';
import { View } from '@tarojs/components';
import classnames from 'classnames';
import CovertIPhoneBottom from '@/components/CovertIPhoneBottom';
import './index.<%= css %>';

type ITabs = {
  key: number | string;
  title: string;
  icon: string;
  number: number;
};

interface ITabsInPage {
  defalultActiveKey: number | string;
  onChangeTab?: (key: number | string, item: any) => void;
  tabs: ITabs[];
  onGetHeight?: (height: number) => void;
}

class TabWithIcon extends PureComponent<ITabsInPage, any> {
  constructor(props) {
    super(props);
    const propsTabs = (props || {}).tabs || [];
    this.state = {
      activeKey: (props || {}).defalultActiveKey || (propsTabs[0] || {}).key,
    };
  }

  // 响应父组件参数变化
  componentDidUpdate(preProps) {
    const { defalultActiveKey } = preProps;
    if (defalultActiveKey !== this.props.defalultActiveKey) {
      // eslint-disable-next-line react/no-did-update-set-state
      this.setState({ activeKey: this.props.defalultActiveKey });
    }
  }

  handleClick = (item) => {
    const { onChangeTab } = this.props;
    this.setState({
      activeKey: item.key,
    });

    onChangeTab && onChangeTab(item.key, item);
  };

  normalizeDot = (num) => (num > 99 ? `99+` : num);

  render() {
    const { activeKey } = this.state;
    const { tabs = [], onGetHeight = () => {} } = this.props;
    return (
      <CovertIPhoneBottom onGetHeight={onGetHeight}>
        <View className="tabs-with-icon-wrapper">
          {tabs.map((item) => (
            <View className="tab-item" key={item.key}>
              <View
                className={classnames('tab-item-inner-content', {
                  active: activeKey === item.key,
                })}
                onClick={() => this.handleClick(item)}
              >
                <View
                  className={`iconfont ${item.icon}`}
                  style={{ fontSize: '52rpx', height: '52rpx', lineHeight: '52rpx', position: 'relative' }}
                >
                  {item.number > 0 && <View className="number-dot">{this.normalizeDot(item.number)}</View>}
                </View>
                <View className="txt">{item.title}</View>
              </View>
            </View>
          ))}
        </View>
      </CovertIPhoneBottom>
    );
  }
}
export default TabWithIcon;
